package com.yoj.model.vo;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yoj.model.codesandbox.JudgeInfo;
import com.yoj.model.entity.QuestionSubmit;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Date;

/**
 * 题目提交封装类
 * 专门给前端返回的对象，可以节约网络传输、过滤字段（脱敏）
 * 和 Question 类相比多了 UserVO、QuestionVO 字段
 */
@Data
@ApiModel(value = "题目提交信息视图")
public class QuestionSubmitVO implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    private Long id;

    @ApiModelProperty(value = "编程语言（枚举类存储）")
    private String language;

    @ApiModelProperty(value = "用户代码")
    private String code;

    @ApiModelProperty(value = "判题信息（json 对象）")
    private JudgeInfo judgeInfo;

    @ApiModelProperty(value = " 枚举类：判题状态（0-待判题、1-判题中、2-成功、3-失败）")
    private Integer status;

    @ApiModelProperty(value = "题目 id（逻辑外键）")
    private Long questionId;

    @ApiModelProperty(value = "创建用户 id（逻辑外键）")
    private Long userId;

    @ApiModelProperty(value = "创建时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createTime;

    @ApiModelProperty(value = "更新时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date updateTime;

    @ApiModelProperty(value = "关联查询用户信息")
    private UserVO userVO;

    @ApiModelProperty(value = "关联对应题目信息")
    private QuestionVO questionVO;

    /**
     * 包装类转对象：VO -> Java对象，存到数据库里
     */
    public static QuestionSubmit voToObj(QuestionSubmitVO questionSubmitVO) {
        if (questionSubmitVO == null) {
            return null;
        }
        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitVO, questionSubmit);
        // judgeConfig 属性需要另作处理
        // 判题配置字符串转json
        JudgeInfo judgeConfigObj = questionSubmitVO.getJudgeInfo();
        if (judgeConfigObj != null) {
            questionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeConfigObj));
        }

        return questionSubmit;
    }

    /**
     * 对象转包装类：Java对象 -> VO，返回给前端
     */
    public static QuestionSubmitVO objToVo(QuestionSubmit questionSubmit) {
        if (questionSubmit == null) {
            return null;
        }
        QuestionSubmitVO questionSubmitVO = new QuestionSubmitVO();
        BeanUtils.copyProperties(questionSubmit, questionSubmitVO);
        // judgeInfo 属性需要另作处理
        // 判题信息字符串转java对象
        String judgeInfoStr = questionSubmit.getJudgeInfo();
        questionSubmitVO.setJudgeInfo(JSONUtil.toBean(judgeInfoStr, JudgeInfo.class));

        return questionSubmitVO;
    }
}